/*

 * Copyright 2008 Dirección Provincial de Informática de la Provincia de Buenos Aires.  All Rights Reserved

 * Dirección Provincial de Informática de la Provincia de Buenos Aires Proprietary and Confidential.

 *

 * You agree to use Your best efforts to protect the software and documentation

 * from unauthorized copy or use. The software source code represents and embodies

 * trade secrets of Dirección Provincial de Informática de la Provincia de Buenos Aires and/or its licensors.

 * The source code and embodied trade secrets are not licensed to you and any modification,

 * addition or deletion is strictly prohibited. You agree not to disassemble, decompile,

 * or otherwise reverse engineer the software in order to discover the source code and/or

 * the trade secrets contained in the source code.

 *

 *

 * Derecho de autor 2008 Dirección Provincial de Informática de la Provincia de Buenos Aires.  Todos los derechos reservados.

 * Propiedad de Dirección Provincial de Informática de la Provincia de Buenos Aires y Confidencial.

 *

 * Por la presente acuerdo hacer mi mayor esfuerzo para proteger el software y la documentación

 * de la copia o el uso no autorizados. El código fuente del software representa e incluye

 * secretos comerciales de Dirección Provincial de Informática de la Provincia de Buenos Aires y/o sus licenciantes. 

 * No se le otorga licencia del código fuente ni los secretos comerciales incluidos;

 * y cualquier modificación, agregado o eliminación se encuentra estrictamente prohibida.

 * Asimismo, por la presente me comprometo a no desarmar, descompilar, o de alguna forma utilizar

 * técnicas de ingeniería inversa sobre el software para descubrir su fuente y/o los

 * secretos comerciales contenidos en el código fuente.

 *

 */

package jmc.ui.front.action;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import jmc.core.dao.Wd041803DAO;
import jmc.core.model.Pdmpro01;
import jmc.core.model.TotalesVDP;
import jmc.core.model.TfVdpTransac;
import jmc.core.model.Usuario;
import jmc.core.model.Wd013103;
import jmc.core.model.Wd016003;
import jmc.core.model.Wd041803;
import jmc.core.model.reports.DataSectoresSelected;
import jmc.core.model.reports.Inventario;
import jmc.core.model.reports.InventarioResumen;
import jmc.core.model.reports.Prefacturacion;
import jmc.core.model.reports.Seguimiento;
import jmc.core.model.reports.UnidIrregularidad;
import jmc.core.service.PdiManager;
import jmc.core.service.SendTravelsManager;
import jmc.ui.front.form.ABMPdiForm;
import jmc.ui.front.form.ABMUsuarioForm;
import jmc.ui.front.form.SendTravelsForm;
import jmc.util.DateUtil;
import jmc.util.core.Reporte;
import jmc.util.core.TipoVista;
import jmc.util.core.Utiles;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.springframework.web.struts.DispatchActionSupport;

import com.ibm.as400.access.AS400;

/**
 * @author Juan Manuel Carrascal.
 * 
 */
public class ServiceSendTravelsAction extends DispatchActionSupport {

	public ActionForward sendTravelsWS(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		
		
		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext()
				.getBean("SendTravelsManager");
		
		String param = sendTravelsManager.getParamOnOff();
		
		if (param != null && param.equals("on")){
			sendTravelsManager.callThreadTfvdp418("", null);
		}
		
		
		
		return null;

	}

		
	public ActionForward setOnOff(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;

		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext()
				.getBean("SendTravelsManager");

		sendTravelsManager.setOnOff(sendTravelsForm.getOnOff());
		
		return mapping.findForward("authenticationOk");

	}	

	public ActionForward procesarLote(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;

		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext()
				.getBean("SendTravelsManager");

		sendTravelsManager.sendTravels(sendTravelsForm.getFechaProceso(), "001");
		
		return mapping.findForward("success_procesarLote");

	}	
	
	public ActionForward loginWs(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
				
		return mapping.findForward("loginWs");

	}

	public ActionForward userWsAuthentication(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
		
		String username = sendTravelsForm.getUsername();
		String password = sendTravelsForm.getPassword();
		
		if(username == null || password == null){
			return mapping.findForward("authenticationFalled");
		}else{
			if(username.equals("operador") && password.equals("pacheco")){
				Usuario usuario = new Usuario();
				usuario.setUsername("Operador");
				usuario.setAutentication(true);
				usuario.setNumCliente(1);
				usuario.setIdPerfil(1l);			
				request.getSession().setAttribute("usuario", usuario);
				return mapping.findForward("authenticationOk");	
			}else{			
				return mapping.findForward("authenticationFalled");		
			}
		}
	}

	public ActionForward preparedListTfVdp420(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
                
		Usuario usuario = (Usuario) request.getSession()
				.getAttribute("usuario");

		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext()
		.getBean("SendTravelsManager");
		
		List<TfVdpTransac> transacList = new ArrayList<TfVdpTransac>();
				
		transacList = sendTravelsManager.getTransacList();
		
		sendTravelsForm.setTransacList(transacList);
		
		sendTravelsForm.setFechaProceso("");
		
		String param = sendTravelsManager.getParamOnOff();
		
		sendTravelsForm.setOnOff(param);
		
		return mapping.findForward("success_preparedListTfVdp420");

	}
	
	public ActionForward downloadFile(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
		
		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext().getBean("SendTravelsManager");				
		
		String fileStr = sendTravelsManager.getRutaArchivoDefault() +  sendTravelsForm.getRutaFile() + ".xml";
		
		File file = new File(fileStr);
		
		int length   = 0;
		
		
		ServletOutputStream sos = response.getOutputStream();
				
		response.setHeader("Content-disposition", "attachment; filename=" + file.getName().replaceAll(" ", "_"));        
		response.setHeader("Pragma", "Public");        
		response.setContentType("application/octet-stream");   
		response.setContentLength((int)file.length());
		
		//
		//  Stream to the requester.
		//
		byte[] bbuf = new byte[2048];
			File fileDownload = file;
			DataInputStream in = new DataInputStream(new FileInputStream(fileDownload));
		
			while ((in != null) && ((length = in.read(bbuf)) != -1))
			{
			sos.write(bbuf,0,length);
		}
		
		sos.flush();
		sos.close();
		in.close();
				
		return null;
	}

	public ActionForward outUser(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		
		request.getSession().removeAttribute("usuario");
		
		return mapping.findForward("success_outUser");
	}

	public ActionForward getDetalle(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
 
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
		
		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext().getBean("SendTravelsManager");
		
		Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
		
		if (sendTravelsForm.getListado().equals("1") || sendTravelsForm.getListado().equals("2") || sendTravelsForm.getListado().equals("3") ||sendTravelsForm.getListado().equals("4") ||sendTravelsForm.getListado().equals("8")){
			List<Wd041803> estadosList = new ArrayList<Wd041803>();
			if (sendTravelsForm.getListado().equals("1")){
				estadosList = sendTravelsManager.getViajesPorEstado("1", usuario.getJobActual());
			}
			if (sendTravelsForm.getListado().equals("2")){
				estadosList = sendTravelsManager.getViajesPorEstado("2", usuario.getJobActual());
			}
			if (sendTravelsForm.getListado().equals("3")){
				estadosList = sendTravelsManager.getViajesPorEstado("3", usuario.getJobActual());
			}
			if (sendTravelsForm.getListado().equals("4")){
				estadosList = sendTravelsManager.getViajesPorEstadoTotal("", usuario.getJobActual());
			}
			
			if (sendTravelsForm.getListado().equals("8")){
				List<Wd013103> sEntregaList = new ArrayList<Wd013103>();
				
				sEntregaList = sendTravelsManager.getSEntregaPorEstadoTotal("", usuario.getJobActual());
				
				sendTravelsForm.setWd013103List(sEntregaList);
				
				sendTravelsForm.setUsuario(usuario);
				
				return mapping.findForward("success_getDetalleSEntrega");
			}

			sendTravelsForm.setWd041803List(estadosList);
			
			sendTravelsForm.setUsuario(usuario);
			
			return mapping.findForward("success_getDetallePorEstado");
			
		}else{
			List<Wd016003> pendientesList = new ArrayList<Wd016003>();  
			if (sendTravelsForm.getListado().equals("5")){
				pendientesList = sendTravelsManager.getPendientesPorEstado("PEND", usuario.getJobActual());
			}
			if (sendTravelsForm.getListado().equals("6")){
				pendientesList = sendTravelsManager.getPendientesPorEstado("RETE", usuario.getJobActual());
			}
			if (sendTravelsForm.getListado().equals("7")){
				pendientesList = sendTravelsManager.getPendientesPorEstado(usuario.getJobActual());
			}

			sendTravelsForm.setWd016003List(pendientesList);
			
			sendTravelsForm.setUsuario(usuario);
			
			return mapping.findForward("success_getDetallePorPendientes");

			
		}
	}
	
	public ActionForward listoVdp(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{		

		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
		
		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext().getBean("SendTravelsManager");								
		
		Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
		
		//System.out.println(sendTravelsForm.getFechaProceso());
		String ff = sendTravelsForm.getFechaProceso();
		if (ff == null){
			ff = usuario.getFechaInventario();
		}else{
			usuario.setFechaInventario(ff);
		}
		String dateDesde = ff.replaceAll("/", "");
		dateDesde = dateDesde.substring(0, 4) + dateDesde.substring(6, 8); 
		
		
		
		System.out.println(dateDesde);
		
		String random = Utiles.getRandomNumberL5();

		//Llamar al programa del AS400 con el random
		sendTravelsManager.callTF0418ACL(usuario.getAs400Online(), Utiles.llenoConZero(String.valueOf(usuario.getNumCliente())), dateDesde, random);
						
		TotalesVDP t = sendTravelsManager.getTotalesVDP(dateDesde, random);
		
		sendTravelsForm.setTotalesVDP(t);		
		
		usuario.setJobActual(random);
		
		request.getSession().setAttribute("usuario", usuario);
				
		sendTravelsForm.setUsuario(usuario);
		
		return mapping.findForward("success_listoVdp");
	}
	
	
	public ActionForward preparedSelectDate(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		
		SendTravelsForm sendTravelsForm = (SendTravelsForm) form;
		
		SendTravelsManager sendTravelsManager = (SendTravelsManager) getWebApplicationContext().getBean("SendTravelsManager");				
		
		return mapping.findForward("success_preparedSelectDate");
	}

	
	
}
